|
Boxing and Unboxing are essential concepts in C#. They form a link between a reference type and a value type. Boxing and Unboxing is made possible because of the .Net framework common type system (CTS) which means that all types, reference and value, derive from the type object. It is possible to call methods on a value, such as 3. Try it in the editor, type the numeral 3 followed by a full stop to invoke IntelliSense. Notice that there are various methods including Equals, GetHashCode, GetType and ToString. These are all inherited from the base CTS object. Boxing is a process by which any value type (or reference type) can be treated as a reference type object and worked on before being unboxed back to its original value type. int
myInteger = 12345;
// myInteger is boxed // myInteger is unboxed Why would you want to do this? Well suppose you need an array of objects that do not have the same type and need to iterate through them. int
a = 3;
decimal b = 4.35; string c = "Hello"; object[] myList = new object[3]; // Box up the value and reference types
together // Unbox the types if (typeof(Unboxed) == int)
Tutorials in this Series
Leave a ReplyClick here to cancel reply.
|







